package com.hula.onion.book.server.spider.platforms.caifuxq;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/1/29.
 */
@Component
public class CaiFuXQSpiderHelper {

    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("nickname", form.getUserName());
        map.put("password", StringUtils.upperCase(DigestUtils.md5Hex(form.getPassword())));
        map.put("loanCommentCode", "");
        return map;
    }


    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {
        try {
            Document dc = Jsoup.parse(html);
            Element el = dc.selectFirst("div.overview-right");
            String amount = el.getAllElements().get(5).text();
            String waitIntrest = el.getAllElements().get(16).text();
            String fWI = StringUtils.remove(waitIntrest, "元");
            String totalIntrest = el.getAllElements().get(23).text();
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setAmount(new BigDecimal(amount));
            accountInfo.setWaitIntrest(new BigDecimal(fWI));
            accountInfo.setTotalIntrest(new BigDecimal(totalIntrest));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }
}
